<script lang="ts" setup>
import FormatFormVue from "@/Components/FormatForm.vue";
import PaginationVue from "@/Components/Pagination.vue";
import CreateUserVue from "./Components/CreateUser.vue";
import UpdateUserVue from "./Components/UpdateUser.vue";
import resetPasswordVue from "./Components/resetPassword.vue";

import { ref, reactive, onBeforeMount, watch } from "vue";
import { ElMessageBox, ElTable, Action } from "element-plus";
import { Plus, Edit, Search, Unlock, RefreshLeft, Close } from "@element-plus/icons-vue";
import { filterAdminUserStatus } from "@/utils/filters";
import { RoleApi, UserApi } from "@/Api";

const form = reactive<RouterConfig.Search>({
   label: ""
});
const formOptions = reactive<FormOptions<RouterConfig.Search>>({
   label: {
      type: "text",
      placeholder: "菜单名称"
   }
});
const tableData = ref<User.Table[]>();
const showaddAdminUser = ref(false);
const showUpdateUser = ref(false);
const loadingTable = ref(false);
const actionUser = ref<User.Table>();
const showResetPassword = ref(false);
const roleList = ref<Role.Table[]>([]);
const laypage = reactive<Laypage>({
   pageNum: 1,
   pageSize: 20,
   total: 10
});

watch([showaddAdminUser, showUpdateUser], ([value0, value1]) => {
   if (!value0 || !value1) submit();
});

async function submit() {
   loadingTable.value = true;

   try {
      const { code, data } = await UserApi.Search({});
      if (code === 200) {
         tableData.value = data;
      }
   } catch (error) {
      console.log("error", error);
   }

   loadingTable.value = false;
}

/** 激活账户 */
async function handlerAction(userId: string) {
   try {
      const { code } = await UserApi.Action({ userId });
      if (code == 200) {
         ElMessage.success("激活成功");
         await submit();
      }
   } catch (error) {
      console.log("error", error);
   }
}

/** 重置密码 */
function resetPassword(user: User.Table) {
   actionUser.value = user;
   showResetPassword.value = true;
}

/** 删除账户
 * @param userId 用户 id
 */
async function removeAdminUser(user: User.Table) {
   try {
      ElMessageBox.confirm("删除当前账户?", "警告", {
         confirmButtonText: "确定",
         type: "warning",
         callback: async (action: Action) => {
            if (action === "confirm") {
               const { code } = await UserApi.Delete({ userId: user.id });
               if (code === 200) {
                  ElMessage.success("删除成功");
                  await submit();
               }
            }
         }
      });
   } catch (error) {
      console.log("error", error);
   }
}

/** 修改用户信息 */
function updateUser(user: User.Table) {
   actionUser.value = user;
   showUpdateUser.value = true;
}

async function getRoleList() {
   try {
      const { code, data } = await RoleApi.Search();
      if (code === 200) {
         roleList.value = data;
      }
   } catch (error) {
      console.log("error", error);
   }
}

function sizeChange(num: number) {
   laypage.pageSize = num;
   submit();
}
function currentChange(num: number) {
   laypage.pageNum = num;
   submit();
}

function handlerCopy(text: string) {
   navigator.clipboard
      .writeText(text)
      .then(() => {
         ElMessage.success("复制成功");
      })
      .catch(() => {
         ElMessage.error("复制失败");
      });
}

onBeforeMount(async () => {
   await submit();
   await getRoleList();
});
</script>

<template>
   <div class="main">
      <div class="content">
         <FormatFormVue :form="form" :form-options="formOptions">
            <template #button>
               <el-button :icon="Plus" type="primary" @click="showaddAdminUser = true"> 添加用户 </el-button>
            </template>
         </FormatFormVue>
         <div class="tabBox shadowCard">
            <el-table
               v-loading="loadingTable"
               :data="tableData"
               stripe
               border
               highlight-current-row
               empty-text="暂无数据"
               tooltip-effect="light"
               row-key="id">
               <el-table-column prop="name" label="显示名称" />
               <el-table-column prop="account" label="用户账号" />
               <el-table-column prop="phone" label="手机号码">
                  <template #default="{ row }: { row: User.Table }">
                     <span v-if="!!row.phone" class="phone" @click="handlerCopy(row.phone)">{{ row.phone }}</span>
                  </template>
               </el-table-column>
               <el-table-column prop="status" label="状态">
                  <template #default="{ row }: { row: User.Table }">
                     <span class="status">
                        {{ filterAdminUserStatus[row.status] }}
                        <el-tooltip effect="dark" content="激活账户" placement="right" v-if="row.status === 'NOT_ACTIVATED'">
                           <el-icon
                              v-if="row.status === 'NOT_ACTIVATED'"
                              class="action"
                              @click="handlerAction(row.id)"
                              size="20">
                              <Unlock />
                           </el-icon>
                        </el-tooltip>
                     </span>
                  </template>
               </el-table-column>
               <el-table-column prop="role_name" label="权限"> </el-table-column>
               <el-table-column prop="created_time" label="注册时间" />
               <el-table-column label="操作" width="280" align="center">
                  <template #default="{ row }: { row: User.Table }">
                     <el-link :icon="RefreshLeft" type="primary" @click="resetPassword(row)">重置密码</el-link>
                     <el-link :icon="Edit" type="primary" @click="updateUser(row)">编辑</el-link>
                     <el-link :icon="Close" type="primary" @click="removeAdminUser(row)">删除</el-link>
                  </template>
               </el-table-column>
            </el-table>
         </div>
         <PaginationVue :laypage="laypage" @size-change="sizeChange" @current-change="currentChange" />
      </div>

      <CreateUserVue v-model="showaddAdminUser" :role-list="roleList" />
      <UpdateUserVue v-model="showUpdateUser" :user-info="actionUser" :role-list="roleList" />
      <resetPasswordVue v-model="showResetPassword" :user-id="actionUser?.id" />
   </div>
</template>

<style lang="scss" scoped>
.main {
   width: 100%;
   height: 100%;
}

.content {
   width: 100%;
   height: 100%;
   display: flex;
   flex-direction: column;
}
.tabBox {
   flex: 1;
   width: 100%;
   position: relative;
   box-sizing: border-box;
   padding: 15px;
   .el-table {
      position: absolute;
      width: calc(100% - 30px);
      height: calc(100% - 30px);
   }
}

.status {
   display: flex;
   width: 100%;
   height: 100%;
   align-items: center;
}

.action {
   cursor: pointer;
   margin-left: 10px;
}

.el-link {
   margin-inline: 5px;
}
</style>
